import 'package:cave_flutter/pages/whl_chat/whl_chat_logic.dart';
import 'package:cave_flutter/style/whl_style.dart';
import 'package:cave_flutter/widgets/brick/brick.dart';
import 'package:cave_flutter/widgets/brick/widget/basic_widget.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:nim_core/nim_core.dart';

class WhlTextMessageItem extends StatelessWidget {
  // final RCIMIWMessage messageModel;
  // final int index;
  NIMMessage message;

  WhlTextMessageItem({super.key, required this.message});

  final logic = Get.find<WhlChatLogic>();

  @override
  Widget build(BuildContext context) {
    // RCIMIWTextMessage textMessage = messageModel as RCIMIWTextMessage;
    // String? translatedText;
    // if (messageModel.extra?.isNotEmpty == true) {
    //   Map extra = jsonDecode(messageModel.extra!);
    //   translatedText = extra['translatedText'];
    // } else {
    //   translatedText = WhlUserUtils.getTranslatedText(textMessage.text ?? '');
    // }
    bool isSend = message.messageDirection == NIMMessageDirection.outgoing;
    return UIColumn(
      crossAxisAlignment: CrossAxisAlignment.start,
      margin: EdgeInsets.only(bottom: 20.h),
      children: [
        UIContainer(
          padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
          // gradientStartColor: messageModel.senderUserId == WhlUserUtils.getId() ? kAppColor('#FFEC45') : Colors.white,
          // gradientEndColor: messageModel.senderUserId == WhlUserUtils.getId() ? kAppColor('#FFEC45') : Colors.white,
          color: isSend ? kAppTextColor : kAppColor('#F5F5F5'),

          decoration: BoxDecoration(
            image: DecorationImage(
              image: AssetImage(
                isSend ? "assets/images/chat-bubble-right.png" : "assets/images/chat-bubble-left.png",
              ),
              // fit: BoxFit.fitWidth,
              centerSlice: isSend ? const Rect.fromLTRB(15, 15, 23, 19) : const Rect.fromLTRB(18, 15, 20, 19),
              /*
              AssetImage(

              ),
               */
            ),
          ),

          // TODO: 自定义聊天气泡
          radius: 8.w,
          constraints: BoxConstraints(maxWidth: Get.width - 180.w, minHeight: 40.h),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              RichText(
                text: TextSpan(children: _getContentSpan(message.content ?? "", isSend: isSend)),
              ),
              // if (translatedText != null)
              //   Container(
              //     margin: EdgeInsets.only(top: 10.h),
              //     padding: EdgeInsets.only(top: 10.h),
              //     decoration: BoxDecoration(border: Border(top: BorderSide(width: 0.5.w, color: kAppColor('#CCCCCC')))),
              //     child: Text(
              //       translatedText,
              //       style: TextStyle(fontSize: 14.sp, color: kAppSubTextColor),
              //     ),
              //   )
            ],
          ),
        ),
        // if (messageModel.senderUserId != WhlUserUtils.getId() && !WhlUserUtils.getIsAutoTranslate() && translatedText == null)
        //   UIText(
        //     margin: EdgeInsets.only(top: 6.h),
        //     text: 'Translate',
        //     fontSize: 11.sp,
        //     textColor: kAppSubTextColor,
        //     marginDrawable: 4.w,
        //     endDrawable: UIImage(
        //       assetImage: 'icon_chat_translate.png',
        //       width: 12.w,
        //       imageColor: kAppSubTextColor,
        //     ),
        //     onTap: () {
        //       logic.onTranslateForChatRoom(messageModel, isManual: true);
        //     },
        //   )
      ],
    );
  }

  List<InlineSpan> _getContentSpan(String text, {bool isSend = true}) {
    List<InlineSpan> _contentList = [];

    RegExp exp =
        // new RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-?=%.]+');
        RegExp(r'(?:(?:https?|ftp):\/\/)?[\w/\-@?^=%&:/~+#.-]+\.[\w/\-@?^=%;\]{[&:",}/~+.#-]+');

    // new RegExp(r'(http|ftp|https)://([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?');
    // text = "如果www.baidu.com这是一段文本但是里面包含了连接";
    Iterable<RegExpMatch> matches = exp.allMatches(text);

    int index = 0;
    matches.forEach((match) {
      /// start 0  end 8
      /// start 10 end 12
      String c = text.substring(match.start, match.end);

      // print('---地址-url:--$c');
      if (match.start == index) {
        index = match.end;
      }
      if (index < match.start) {
        String a = text.substring(index, match.start);
        // print('---地址-内容AAAA--$a');
        index = match.end;
        _contentList.add(
          TextSpan(text: a, style: TextStyle(fontSize: 14.sp, color: isSend ? Colors.white : kAppTextColor)),
        );
      }

      // if (RegexUtil.isURL(c)) {
      _contentList.add(TextSpan(
          text: c,
          style: TextStyle(color: Colors.blue, decoration: TextDecoration.underline, fontSize: 15.sp),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              // Get.to(WebViewExample(
              //   url: text.substring(match.start, match.end),
              // ));
              if (!c.contains('http')) {
                // launch('http://$c');
              } else {
                // launch(c);
              }
            }));
      // } else {
      //   _contentList.add(
      //     TextSpan(text: c,style: TextStyle(
      //         fontSize: 28.sp, color: isSend ? Colors.white : kAppTextColor)),
      //   );
      // }
    });
    if (index < text.length) {
      String a = text.substring(index, text.length);
      // print('---地址-内容BBBB--$a');
      _contentList.add(
        TextSpan(text: a, style: TextStyle(fontSize: 14.sp, color: isSend ? Colors.white : kAppTextColor)),
      );
    }

    return _contentList;
  }
}
